<?php 
class Md_UserPoint extends WdkModel
{
	public function __construct()
	{
		parent::__construct();
		$this->_init();
	}
	
	private function _init()
	{
		$this->table	= 'user_point';
		$this->order	= array("`user_point_seq` DESC");
	}
	public function count($where=array())
	{
		$where = (array) $where;
		$sql = sprintf(	"SELECT
							COUNT(*) AS `cnt`
						FROM `{$this->table}`
						%s"
						, (count($where) > 0 ? ' WHERE '.implode(' AND ', $where) : '')
					);
		$this->dbo->execute($sql);
		if($this->dbo->numRows() > 0)
		{
			$row =$this->dbo->row();
			return $row['cnt'];
		}
		throw new NoRecordException();
	}
	public function getList($fields=array('*'), $where=array(), $order=array())
	{
		$fields = (array) $fields;
		$where = (array) $where;
		$order = array_merge($this->order, (array) $order);
		$this->setOrder($order);
		foreach($fields as $idx=>$field)
		{
			$fields[$idx] = "`up`.".$field;
		}
		
		$sql = sprintf(	"SELECT 
							%s
							, `u`.`user_login_id`, `u`.`user_name`, `u`.`user_nick`
						FROM `{$this->table}` AS `up`
						LEFT JOIN `user` as `u` ON (`u`.`user_seq` = `up`.`fk_user_seq`)
						%s %s %s %s"
						, (count($fields) > 0 ? implode(',', $fields) : '')
						, (count($where) > 0 ? 'WHERE '.implode(' AND ', $where) : '')
						, (count($this->group) > 0 ? 'GROUP BY '.implode(', ', $this->group) : '')
						, (count($order) > 0 ? 'ORDER BY '.implode(', ', $order) : '')
						, (strlen($this->limit) > 0) ? 'LIMIT '.$this->limit : ''
					);
		$this->dbo->execute($sql);
		if($this->dbo->numRows() > 0)
		{
			return $this->dbo->rows();    		
		}
		throw new NoRecordException();
	}
	
	public function getData($fields=array('*'), $where=array())
	{
		$fields = (array) $fields;
		$where = (array) $where;
		foreach($fields as $idx=>$field)
		{
			$fields[$idx] = "`up`.".$field;
		}
		$sql = sprintf(	"SELECT 
							%s
							, `u`.`user_login_id`, `u`.`user_name`, `u`.`user_nick`
						FROM `{$this->table}` AS `up`
						LEFT JOIN `user` as `u` ON (`u`.`user_seq` = `up`.`fk_user_seq`)
						%s LIMIT 0,1 "
						, (count($fields) > 0 ? implode(',', $fields) : '')
						, (count($where) > 0 ? 'WHERE '.implode(' AND ', $where) : '')
					);
		$this->dbo->execute($sql);
		if($this->dbo->numRows() > 0)
		{
			return $this->dbo->row();    		
		}
		throw new NoRecordException();
	}
	
	/**
	 *	Select query for Classes..
	 *  @author	kinuz
	 *  @since	2011. 3. 25
	 */
	public function cLoad($user_point_seq)
	{
		return $this->getData("*", "`user_point_seq` = {$this->escape($user_point_seq)}");
	}
	
	public function getUserPoints($user_seq)
	{
		$sql = "SELECT 
					SUM(`user_point_amount`) AS `user_points`
				FROM `{$this->table}` AS `up`
				WHERE `up`.`fk_user_seq` = {$user_seq}";
		$this->dbo->execute($sql);
		if($this->dbo->numRows() > 0)
		{
			$data = $this->dbo->row();
			return $data['user_points'];    		
		}
		return 0;
	}
}